import axios from 'axios'
import type { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios'
import router from '../router/index.ts'
// import { MessageBox } from 'element-plus';
import { debounce } from './utils.js'
// import store from '../store/index'
import { getToken, removeToken } from './auth.js'
import Config from '@/settings.js'

interface ResponseData {
  code: number
  message?: string
  data?: any
}

// 请求出错
const onRequestError = debounce(({ message, ...rest }: { message: string; code?: number }) => {
  console.warn(`http请求出错: [${message}], code: ${rest.code}`)
  return rest
}, 400)

const TokenExprie = debounce(() => {
  // MessageBox 相关代码...
  removeToken()
  router.push({ path: '/Login' })
}, 1000)

// 创建axios实例
const service: AxiosInstance = axios.create({
  timeout: Config.timeout // 请求超时时间
})

// request拦截器
service.interceptors.request.use(
  (config: AxiosRequestConfig) => {
    if (getToken()) {
      config.headers = config.headers || {}
      config.headers['Authorization'] = 'Bearer ' + getToken()
    }
    config.headers = {
      ...config.headers,
      'Accept': 'application/json',
      'Content-Type': 'application/json'
    }
    return config
  },
  (error) => Promise.reject(error)
)

// response 拦截器
service.interceptors.response.use(
  (response: AxiosResponse<ResponseData>) => {
    const code = response.data.code
    if (code < 200 || code > 300) { 
      if (code === 401) {
        TokenExprie()
        return Promise.reject('error')
      } else if (code === 403) {
        window.location.href = window.location.origin + '/License'
      } else {
        onRequestError({ message: response.data.message || '请求错误' })
        return Promise.reject('error')
      }
    } else {
      if (response.config.responseType === 'blob' && response.config.method === 'post') {
        return new Promise((resolve, reject) => {
          if (response.headers['content-type']?.includes('json')) {
            const reader = new FileReader()
            reader.onload = () => {
              try {
                const { result } = reader
                const errorInfo = JSON.parse(result as string)
                if (errorInfo.code !== 200) {
                  onRequestError(errorInfo)
                  reject(errorInfo)
                } else {
                  resolve(errorInfo)
                }
              } catch (err) {
                resolve(response)
              }
            }
            reader.onerror = err => {
              reject(err)
            }
            reader.readAsText(response.data)
          } else {
            resolve(response)
          }
        })
      }
      return response.data
    }
  },
  (error) => {
    let code = 0
    try {
      code = error.response.data.code
    } catch (e) {
      if (error.toString().indexOf('Error: timeout') !== -1) {
        return Promise.reject(onRequestError({ message: '网络请求超时' }))
      }
    }
    if (code) {
      if (code === 401) {
        TokenExprie()
      } else if (code === 403) {
        router.push({ path: '/401' })
      } else {
        const errorMsg = error.response?.data?.message
        if (errorMsg !== undefined) {
          onRequestError({ message: errorMsg })
        }
      }
    }
  }
)

export default service 